import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

const String kGuessSpKey = "guess-config";
const String kMuYuSpKey = "mu-yu-config";
const String kPaperSpKey = "paper-config";

/// 单例模式访问对象和存储配置
class SpStorage {
  SpStorage._(); // 私有化构造

  static SpStorage? _storage;

  // 提供实例对象的访问路径
  static SpStorage get instance {
    _storage = _storage ?? SpStorage._();
    return _storage!;
  }

  SharedPreferences? _sp;

  Future<void> initSpWhenNull() async {
    if (_sp != null) return;
    _sp = _sp ?? await SharedPreferences.getInstance();
  }

  /// 保存猜数
  Future<bool> saveGuess({required bool guessing, required int value}) async {
    await initSpWhenNull();
    String content = json.encode({'guessing': guessing, 'value': value});
    return _sp!.setString(kGuessSpKey, content);
  }

  /// 读取猜数
  Future<Map<String, dynamic>> readGuessConfig() async {
    await initSpWhenNull();
    String content = _sp!.getString(kGuessSpKey) ?? "{}";
    return json.decode(content);
  }

  /// 保存木鱼
  Future<bool> saveMuYu({
    required int counter,
    required int activeImageIndex,
    required int activeAudioIndex,
  }) async {
    await initSpWhenNull();
    String content = json.encode({
      'counter': counter,
      'activeImageIndex': activeImageIndex,
      'activeAudioIndex': activeAudioIndex
    });
    return _sp!.setString(kMuYuSpKey, content);
  }

  /// 读取木鱼
  Future<Map<String, dynamic>> readMuYuConfig() async {
    await initSpWhenNull();
    String content = _sp!.getString(kMuYuSpKey) ?? "{}";
    return json.decode(content);
  }

  /// 保存白板
  Future<bool> savePaper({
    required int activeColorIndex,
    required int activeStrokeWidthIndex,
  }) async {
    await initSpWhenNull();
    String content = json.encode({
      'activeColorIndex': activeColorIndex,
      'activeStrokeWidthIndex': activeStrokeWidthIndex
    });
    return _sp!.setString(kPaperSpKey, content);
  }

  /// 读取白板
  Future<Map<String, dynamic>> readPaperConfig() async {
    await initSpWhenNull();
    String content = _sp!.getString(kPaperSpKey) ?? "{}";
    return json.decode(content);
  }
}
